import api from './config'
import logger from '../utils/logger.js'

/**
 * 创建新比赛
 * @param {Object} contestData - 比赛数据
 * @returns {Promise} API响应
 */
export const createContest = async (contestData) => {
  try {
    logger.log('➕ [API] 创建新比赛...')
    logger.log('📋 [API] 比赛数据:', contestData)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/addCompetition')
    logger.log('📊 [API] 请求方法: POST')
    
    const response = await api.post('/goc/competition/addCompetition', contestData)
    
    logger.log('✅ [API] 比赛创建成功')
    logger.log('📄 [API] 完整响应:', response)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 创建比赛失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 获取比赛列表
 * @param {Object} params - 查询参数
 * @returns {Promise} API响应
 */
export const getContestList = async (params = {}) => {
  try {
    logger.log('📚 [API] 获取比赛列表...')
    logger.log('📋 [API] 查询参数:', params)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/listCompetition')
    logger.log('📊 [API] 请求方法: GET')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    const response = await api.get('/goc/competition/listCompetition', {
      params: params
    })
    
    logger.log('✅ [API] 比赛列表获取成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📊 [API] 响应状态码:', response?.status)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 获取比赛列表失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 获取比赛详情
 * @param {number} contestId - 比赛ID
 * @returns {Promise} API响应
 */
export const getContestDetail = async (contestId) => {
  try {
    logger.log('🔍 [API] 获取比赛详情...')
    logger.log('🆔 [API] 比赛ID:', contestId)
    logger.log('🆔 [API] 比赛ID类型:', typeof contestId)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/readCompetition')
    logger.log('📊 [API] 请求方法: GET')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    // 🔥 修复大整数精度丢失：保持字符串格式，不转换为number
    const id = String(contestId)
    logger.log('📦 [API] 处理后的比赛ID:', id, '类型:', typeof id)
    logger.log('📦 [API] 比赛ID长度:', id.length, '位')
    
    const response = await api.get('/goc/competition/readCompetition', {
      params: { id: id }  // 以字符串形式传递，后端接收时会自动转换
    })
    
    logger.log('✅ [API] 比赛详情获取成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📊 [API] 响应状态码:', response?.status)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 获取比赛详情失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 更新比赛
 * @param {Object} contestData - 比赛数据
 * @returns {Promise} API响应
 */
export const updateContest = async (contestData) => {
  try {
    logger.log('✏️ [API] 更新比赛...')
    logger.log('📋 [API] 比赛数据:', contestData)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/updateCompetition')
    logger.log('📊 [API] 请求方法: PUT')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    const response = await api.put('/goc/competition/updateCompetition', contestData)
    
    logger.log('✅ [API] 比赛更新成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📊 [API] 响应状态码:', response?.status)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 更新比赛失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 删除比赛
 * @param {string} contestId - 比赛ID
 * @returns {Promise} API响应
 */
export const deleteContest = async (contestId) => {
  try {
    logger.log('🗑️ [API] 删除比赛...')
    logger.log('🆔 [API] 比赛ID:', contestId)
    logger.log('🆔 [API] 比赛ID类型:', typeof contestId)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/deleteCompetition')
    logger.log('📊 [API] 请求方法: DELETE')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    // 🔥 保持字符串格式，避免大整数精度丢失（后端会自动转换为integer）
    const id = String(contestId)
    logger.log('📦 [API] 处理后的比赛ID:', id, '类型:', typeof id)
    logger.log('📦 [API] 比赛ID长度:', id.length, '位')
    
    const response = await api.delete('/goc/competition/deleteCompetition', {
      params: { id: id }
    })
    
    logger.log('✅ [API] 比赛删除成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📊 [API] 响应状态码:', response?.status)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 删除比赛失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 参加比赛（报名比赛）
 * @param {Object} registerData - 报名数据
 * @returns {Promise} API响应
 */
export const registerContest = async (registerData) => {
  try {
    logger.log('🎯 [API] 参加比赛...')
    logger.log('📋 [API] 报名数据:', registerData)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/registerCompetition')
    logger.log('📊 [API] 请求方法: POST')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    const response = await api.post('/goc/competition/registerCompetition', registerData)
    
    logger.log('✅ [API] 参加比赛成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📊 [API] 响应状态码:', response?.status)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 参加比赛失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 获取比赛选手列表
 * @param {string|number} competitionId - 比赛ID
 * @returns {Promise} API响应
 */
export const getCompetitionPlayers = async (competitionId) => {
  try {
    logger.log('👥 [API] 获取比赛选手列表...')
    logger.log('🆔 [API] 比赛ID:', competitionId)
    logger.log('🆔 [API] 比赛ID类型:', typeof competitionId)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/competitionPlayers')
    logger.log('📊 [API] 请求方法: GET')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    // 保持字符串格式，避免大整数精度丢失
    const id = String(competitionId)
    logger.log('📦 [API] 处理后的比赛ID:', id, '类型:', typeof id)
    logger.log('📦 [API] 比赛ID长度:', id.length, '位')
    
    const response = await api.get('/goc/competition/competitionPlayers', {
      params: { competitionId: id }
    })
    
    logger.log('✅ [API] 选手列表获取成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📊 [API] 响应状态码:', response?.status)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 获取选手列表失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 移除比赛选手
 * @param {string|number} competitionId - 比赛ID
 * @param {string|number} userId - 用户ID（19位数）
 * @returns {Promise} API响应
 */
export const removeCompetitionPlayer = async (competitionId, userId) => {
  try {
    logger.log('🗑️ [API] 移除比赛选手...')
    logger.log('🆔 [API] 比赛ID:', competitionId)
    logger.log('🆔 [API] 比赛ID类型:', typeof competitionId)
    logger.log('👤 [API] 用户ID:', userId)
    logger.log('👤 [API] 用户ID类型:', typeof userId)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/removePlayer')
    logger.log('📊 [API] 请求方法: DELETE')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    // 保持字符串格式，避免大整数精度丢失（特别是19位的用户ID）
    const compId = String(competitionId)
    const usrId = String(userId)
    logger.log('📦 [API] 处理后的比赛ID:', compId, '类型:', typeof compId, '长度:', compId.length, '位')
    logger.log('📦 [API] 处理后的用户ID:', usrId, '类型:', typeof usrId, '长度:', usrId.length, '位')
    
    const response = await api.delete('/goc/competition/removePlayer', {
      params: { 
        competitionId: compId,
        userId: usrId
      }
    })
    
    logger.log('✅ [API] 选手移除成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📊 [API] 响应状态码:', response?.status)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 移除选手失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 提交比赛成绩
 * @param {Object} submitData - 提交数据
 * @returns {Promise} API响应
 */
export const submitContestResult = async (submitData) => {
  try {
    logger.log('📤 [API] 提交比赛成绩...')
    logger.log('📋 [API] 提交数据:', submitData)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/submit-result')
    logger.log('📊 [API] 请求方法: POST')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    // 保持字符串格式，避免大整数精度丢失
    const requestData = {
      competitionId: String(submitData.competitionId),
      totalScore: parseInt(submitData.totalScore),
      totalTime: parseInt(submitData.totalTime),
      submitTime: submitData.submitTime || new Date().toISOString().replace('T', ' ').substring(0, 19),
      questionScores: submitData.questionScores || []
    }
    
    logger.log('📦 [API] 处理后的提交数据:', requestData)
    logger.log('🆔 [API] 比赛ID:', requestData.competitionId, '类型:', typeof requestData.competitionId)
    
    const response = await api.post('/goc/competition/submit-result', requestData)
    
    logger.log('✅ [API] 比赛成绩提交成功')
    logger.log('📄 [API] 完整响应:', response)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 提交比赛成绩失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

/**
 * 获取比赛成绩排名
 * @param {string|number} competitionId - 比赛ID
 * @returns {Promise} API响应
 */
export const getContestRank = async (competitionId) => {
  try {
    logger.log('📊 [API] 获取比赛成绩排名...')
    logger.log('🆔 [API] 比赛ID:', competitionId)
    logger.log('🆔 [API] 比赛ID类型:', typeof competitionId)
    logger.log('🌐 [API] 请求地址: /api/goc/competition/rank')
    logger.log('📊 [API] 请求方法: GET')
    logger.log('🔑 [API] 将令牌放到请求头中')
    
    // 保持字符串格式，避免大整数精度丢失
    const id = String(competitionId)
    logger.log('📦 [API] 处理后的比赛ID:', id, '类型:', typeof id)
    
    const response = await api.get('/goc/competition/rank', {
      params: { competitionId: id }
    })
    
    logger.log('✅ [API] 比赛成绩排名获取成功')
    logger.log('📄 [API] 完整响应:', response)
    logger.log('📦 [API] 响应数据:', response?.data)
    
    return response
    
  } catch (error) {
    logger.error('❌ [API] 获取比赛成绩排名失败:', error)
    logger.error('🔍 [API] 错误详情:', {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      url: error.config?.url,
      method: error.config?.method
    })
    throw error
  }
}

